<template>
  <p>
    <button @click="add">
      <i class="ace-icon fa fa-edit"></i>
      新增
    </button>
    &nbsp;
    <button @click="refresh">
      <i class="ace-icon fa fa-undo"></i>
      刷新
    </button>
  </p>
  <table id="simple-table" class="table  table-bordered table-hover">
    <thead>
      <tr>
          <th>id</th>
          <th>角色</th>
          <th>描述</th>
          <th>操作</th>
      </tr>
    </thead>

    <tbody>
    <tr v-for="role in roles" :key="role.id">
          <td>{{ role.id }}</td>
          <td>{{ role.name }}</td>
          <td>{{ role.desc }}</td>
      <td>
        <div class="btn-group">
          <button v-on:click="editUser(role)" class="btn btn-xs btn-info">
            <i class="ace-icon fa fa-user bigger-120"></i>
          </button>

          <button @click="editResource(role)" class="btn btn-xs btn-info">
            <i class="ace-icon fa fa-list bigger-120"></i>
          </button>

          <button @click="edit(role)" class="btn btn-xs btn-info">
            <i class="ace-icon fa fa-pencil bigger-120"></i>
          </button>

          <button @click="del(role.id)" class="btn btn-xs btn-danger">
            <i class="ace-icon fa fa-trash-o bigger-120"></i>
          </button>
        </div>
      </td>
    </tr>
    </tbody>
  </table>
  <!-- 分页插件 -->
  <pagination ref="paginationRef" :list="getRoleList" />

  <!-- Modal -->
  <div class="modal fade" id="form-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">表单</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal">
                 <div class="form-group">
                   <label class="col-sm-2 control-label">角色</label>
                   <div class="col-sm-10">
                   <input v-model="role.name" type="text" class="form-control">
                </div>
              </div>
                 <div class="form-group">
                   <label class="col-sm-2 control-label">描述</label>
                   <div class="col-sm-10">
                   <input v-model="role.desc" type="text" class="form-control">
                </div>
              </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button @click="saveRole" type="button" class="btn btn-primary">保存</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 编辑权限Modal -->
  <div class="modal fade" id="role-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">角色资源关联配置</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal">
            <ul id="tree" class="ztree"></ul>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button @click="saveRoleResource" type="button" class="btn btn-primary">保存</button>
        </div>
      </div>
    </div>
  </div>
  <!-- 角色用户关联配置 -->
  <div id="user-modal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">角色用户关联配置</h4>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-md-6">
              <table id="user-table" class="table table-hover">
                <tbody>
                <tr v-for="user in users">
                  <td>{{user.loginName}}</td>
                  <td class="text-right">
                    <a @click="addUser(user)" href="javascript:;" class="">
                      <i class="ace-icon fa fa-arrow-circle-right blue"></i>
                    </a>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
            <div class="col-md-6">
              <table id="role-user-table" class="table table-hover">
                <tbody>
                <tr v-for="user in roleUsers">
                  <td>{{user.loginName}}</td>
                  <td class="text-right">
                    <a @click="deleteUser(user)" href="javascript:;" class="">
                      <i class="ace-icon fa fa-trash blue"></i>
                    </a>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-white btn-default btn-round" data-dismiss="modal">
            <i class="ace-icon fa fa-times"></i>
            关闭
          </button>
          <button type="button" class="btn btn-white btn-info btn-round" v-on:click="saveUser()">
            <i class="ace-icon fa fa-plus blue"></i>
            保存
          </button>
        </div>
      </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->
</template>

<script>
import axios from "axios";
import {onMounted, ref} from "vue";
import pagination from "@/components/pagination";

export default {
  name: "Role",
  components: {
    pagination,
  },
  setup() {
    // roles 数组
    const roles = ref([]);
    const role = ref({}); // 保存角色表单
    const paginationRef = ref(null);
    const resources = ref([]); // 资源
    const users = ref([]); // 用户
    const roleUsers = ref([]); // 有角色的用户

    // 刷新
    const refresh = () => {
      getRoleList(1);
    }

    // 获取角色列表
    const getRoleList = (page) => {
      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/system/admin/role/list",
          {
            page: page,
            size: paginationRef.value.size
          }
      ).then((response) => {
        Loading.hide();
        const resp = response.data;
        roles.value = resp.content.list;
        paginationRef.value.render(page, resp.content.total);
      })
    }

    // 保存角色
    const saveRole = () => {
      // 保存参数校验
      if ( 1 != 1
                || !Validator.require(role.value.id, "id")
                || !Validator.require(role.value.name, "角色")
                || !Validator.length(role.value.name, "角色", 1, 50)
                || !Validator.require(role.value.desc, "描述")
                || !Validator.length(role.value.desc, "描述", 1, 100)
        )
      {
        return;
      }

      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/system/admin/role/save", role.value).then((response) => {
        const resp = response.data;
        if (resp.success) {
          Loading.hide();
          $('#form-modal').modal('hide');
          Toast.success("保存成功");
          getRoleList(1);
        } else {
          Loading.hide();
          $('#form-modal').modal('hide');
          Toast.warning(resp.message);
        }
      })
    }

    // 删除角色
    const del = (id) => {
      Confirm.show("删除后不可恢复，确认删除？", function () {
        Loading.show();
        axios.delete(process.env.VUE_APP_SERVER + "/system/admin/role/delete/" + id).then((response) => {
          const resp = response.data;
          if (resp.success) {
            //$('#form-modal').modal('hide');
            getRoleList(1);
          }
        })
        Toast.success("删除成功");
      })
    }

    // 添加角色
    const add = () => {
      role.value = {};
      $('#form-modal').modal('show');
    }

    // 修改角色
    const edit = (param) => {
      role.value = $.extend({}, param);
      $('#form-modal').modal('show');
    }

    /**
     * 配置
     * @param param
     */
    const editResource = (param) => {
      role.value = $.extend({}, param);
      loadResource();
      $('#role-modal').modal('show');
    }

    /**
     * 加载资源树
     */
    const loadResource = () => {
      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/system/admin/resource/list").then((response) => {
        Loading.hide();
        const resp = response.data;
        resources.value = resp.content;
        initZTree(); // 加载资源树
        loadRoleResource(); // 自动勾选资源树
      })
    }

    /**
     * 初始化树
     */
    const initZTree = () => {
      var setting = {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            idKey: "id",
            pIdKey: "parent",
            rootPId: '',
            enable: true
          }
        }
      };
      var zNodes = resources.value;

      tree.value = $.fn.zTree.init($("#tree"), setting, zNodes);
      tree.value.expandAll(true);// 展开树
    }

    /**
     * 保存角色资源
     */
    const saveRoleResource = () => {
      let checkedNodes = tree.value.getCheckedNodes();
      console.log("选择的资源节点", checkedNodes);
      if (checkedNodes.length === 0) {
        Toast.warning("请选择资源");
        return;
      }

      Loading.show();
      let resourceIds = [];
      for (let key in checkedNodes) {
        resourceIds.push(checkedNodes[key].id);
      }
      axios.post(process.env.VUE_APP_SERVER + "/system/admin/role/save-resource", {
        id: role.value.id,
        resourceIds: resourceIds
      }).then((response) => {
        const resp = response.data;
        if (resp.success) {
          Toast.success("保存成功");
          Loading.hide();
        } else {
          Toast.error("保存失败");
        }
      })
    }

    /**
     * 获取角色的资源
     */
    const loadRoleResource = () => {
      // 先清空勾选
      tree.value.checkAllNodes(false);
      axios.post(process.env.VUE_APP_SERVER + "/system/admin/role/list-resource/" + role.value.id).then((response) => {
        let resp = response.data;
        if (resp.success) {
          let resourceIds = resp.content;
          for (let key in resourceIds) {
            let node = tree.value.getNodeByParam("id", resourceIds[key]);
            tree.value.checkNode(node, true, false);
          }
        }
      })
    }


    /**
     * 点击【用户】
     */
    const editUser = (param) => {
      role.value = $.extend({}, param);
      listUser();
      roleUsers.value = [];
      $("#user-modal").modal("show");
    }

    /**
     * 查询所有用户
     */
    const listUser = () => {
      axios.post(process.env.VUE_APP_SERVER + '/system/admin/user/list', {
        page: 1,
        size: 9999
      }).then((response)=>{
        let resp = response.data;
        if (resp.success) {
          users.value = resp.content.list;
          listRoleUsers();
        } else {
          Toast.warning(resp.message);
        }
      })
    }

    /**
     * 添加用户到右边
     */
    const addUser = (param) => {
      // 判读此用户是否已经添加过
      for (let key in roleUsers.value) {
        if (roleUsers.value[key].id === param.id) {
          return;
        }
      }
      roleUsers.value.push(param);
    }

    /**
     * 移除右边的用户
     */
    const deleteUser = (param) => {
      Tool.removeObj(roleUsers.value, param);
    }

    /**
     * 角色用户模态框点击【保存】
     */
    const saveUser = () => {
      let users = roleUsers.value;

      // 保存时，只需要保存用户id，所以使用id数组进行参数传递
      let userIds = [];
      for (let i = 0; i < users.length; i++) {
        userIds.push(users[i].id);
      }
      axios.post(process.env.VUE_APP_SERVER + '/system/admin/role/save-user', {
        id: role.value.id,
        userIds: userIds
      }).then((response)=>{
        let resp = response.data;
        if (resp.success) {
          Toast.success("保存成功!");
        } else {
          Toast.warning(resp.message);
        }
      })
    }

    /**
     * 查询角色关联的用户
     */
    const listRoleUsers = () => {
      axios.get(process.env.VUE_APP_SERVER + '/system/admin/role/list-user/' + role.value.id).then((response)=>{
        let resp = response.data;
        if (resp.success) {
          let userIds = resp.content;
          for (let key in userIds) {
            for (let i = 0; i < users.value.length; i++) {
              if (userIds[key] === users.value[i].id) {
                roleUsers.value.push(users.value[i]);
              }
            }
          }
        }
      })
    }

    // 初始加载第一页
    onMounted(() => {
      getRoleList(1);
    })

    return {
      roles,
      refresh,
      paginationRef,
      getRoleList,
      add,
      saveRole,
      role,
      edit,
      del,
      editResource,
      saveRoleResource,
      editUser,
      users,
      addUser,
      deleteUser,
      roleUsers,
      saveUser
    }
  }
}
</script>

<style scoped>

</style>